<?php 

require_once '../../config.php';

visitors_ping(session_id());
$visitor = visitors_get_by_session_id(session_id());

if (!empty($_GET['windowState'])) {
  visitors_update_window_state(session_id(), $_GET['windowState']);
}

if (!empty($_GET['message'])) {
  messages_send_from_visitor($_GET['message'], $visitor);
}

if ($visitor['windowState'] == 'shown') {
  messages_mark_incoming_as_read(session_id());
}

$messages = messages_get(session_id());
?>

monkeyTalkWidget.messages=[];
monkeyTalkWidget.widgetMessages.innerHTML = "";

<?php
foreach ($messages as $m) {
  echo "monkeyTalkWidget.addMessage([encodeURI(\"{$m['senderName']}\"), encodeURI(\"{$m['message']}\"), \"{$m['id']}\"]);";
}
if ($visitor['incomingUnread'] == 1) {
  echo "monkeyTalkWidget.onMessageReceived([encodeURI(\"{$m['senderName']}\"), encodeURI(\"{$m['message']}\"), \"{$m['id']}\"]);";
}

echo "monkeyTalkWidget.setPingState(\"ok\");";
